<template>
  <div class="connection-status" :class="statusClass">
    <!-- Connection Status Indicator -->
    <div class="status-indicator" v-if="showIndicator">
      <div class="status-icon" :class="iconClass">
        <div class="pulse" v-if="isConnecting || isReconnecting"></div>
      </div>
      <span class="status-text">{{ statusText }}</span>
    </div>

    <!-- Detailed Status Panel -->
    <div class="status-panel" v-if="showDetails">
      <div class="panel-header">
        <h3>连接状态</h3>
        <button class="close-btn" @click="showDetails = false">×</button>
      </div>
      
      <div class="panel-content">
        <div class="status-row">
          <span class="label">状态:</span>
          <span class="value" :class="statusClass">{{ statusText }}</span>
        </div>
        
        <div class="status-row" v-if="connectionInfo.lastConnectedAt">
          <span class="label">上次连接:</span>
          <span class="value">{{ formatTime(connectionInfo.lastConnectedAt) }}</span>
        </div>
        
        <div class="status-row" v-if="connectionInfo.lastDisconnectedAt && !isConnected">
          <span class="label">断开时间:</span>
          <span class="value">{{ formatTime(connectionInfo.lastDisconnectedAt) }}</span>
        </div>
        
        <div class="status-row" v-if="reconnectAttempts > 0">
          <span class="label">重连次数:</span>
          <span class="value">{{ reconnectAttempts }}/{{ maxReconnectAttempts }}</span>
        </div>
        
        <div class="status-row" v-if="connectionInfo.offlineMessageCount > 0">
          <span class="label">离线消息:</span>
          <span class="value">{{ connectionInfo.offlineMessageCount }} 条待同步</span>
        </div>
        
        <div class="status-row">
          <span class="label">连接质量:</span>
          <span class="value" :class="`quality-${connectionQuality}`">
            {{ qualityText }}
          </span>
        </div>
        
        <div class="error-message" v-if="error">
          <div class="error-icon">⚠️</div>
          <div class="error-text">{{ error }}</div>
        </div>
      </div>
      
      <div class="panel-actions">
        <button 
          class="action-btn retry-btn" 
          @click="handleReconnect"
          :disabled="!canRetry || isConnecting || isReconnecting"
          v-if="!isConnected"
        >
          {{ isReconnecting ? '重连中...' : '重新连接' }}
        </button>
        
        <button 
          class="action-btn disconnect-btn" 
          @click="handleDisconnect"
          :disabled="isConnecting || isReconnecting"
          v-if="isConnected"
        >
          断开连接
        </button>
        
        <button 
          class="action-btn clear-btn" 
          @click="handleClearError"
          v-if="error"
        >
          清除错误
        </button>
        
        <button 
          class="action-btn sync-btn" 
          @click="handleSyncOfflineMessages"
          :disabled="!isConnected || connectionInfo.offlineMessageCount === 0"
          v-if="connectionInfo.offlineMessageCount > 0"
        >
          同步离线消息
        </button>
      </div>
    </div>

    <!-- Offline Message Banner -->
    <div class="offline-banner" v-if="connectionInfo.offlineMessageCount > 0 && !showDetails">
      <div class="banner-content">
        <span class="banner-icon">📤</span>
        <span class="banner-text">
          {{ connectionInfo.offlineMessageCount }} 条消息待同步
        </span>
        <button class="banner-action" @click="handleSyncOfflineMessages" :disabled="!isConnected">
          {{ isConnected ? '立即同步' : '等待连接' }}
        </button>
      </div>
    </div>

    <!-- Connection Quality Indicator -->
    <div class="quality-indicator" v-if="isConnected && showQualityIndicator">
      <div class="quality-bars">
        <div class="bar" :class="{ active: connectionQuality !== 'offline' }"></div>
        <div class="bar" :class="{ active: connectionQuality === 'good' }"></div>
        <div class="bar" :class="{ active: connectionQuality === 'good' }"></div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, onMounted, onUnmounted } from 'vue'
import { useConnectionStore } from '@/stores/connection'
import { formatDistanceToNow } from '@/utils/format'

interface Props {
  showIndicator?: boolean
  showQualityIndicator?: boolean
  autoHide?: boolean
  autoHideDelay?: number
}

const props = withDefaults(defineProps<Props>(), {
  showIndicator: true,
  showQualityIndicator: false,
  autoHide: true,
  autoHideDelay: 3000
})

const connectionStore = useConnectionStore()
const showDetails = ref(false)
let autoHideTimer: NodeJS.Timeout | null = null

// Computed properties
const isConnected = computed(() => connectionStore.isConnected)
const isConnecting = computed(() => connectionStore.isConnecting)
const isReconnecting = computed(() => connectionStore.isReconnecting)
const reconnectAttempts = computed(() => connectionStore.reconnectAttempts)
const maxReconnectAttempts = computed(() => connectionStore.maxReconnectAttempts)
const error = computed(() => connectionStore.error)
const connectionQuality = computed(() => connectionStore.connectionQuality)
const canRetry = computed(() => connectionStore.canRetry)
const connectionInfo = computed(() => connectionStore.connectionInfo)

const statusClass = computed(() => {
  if (isConnecting.value) return 'connecting'
  if (isReconnecting.value) return 'reconnecting'
  if (isConnected.value) return 'connected'
  if (error.value) return 'error'
  return 'disconnected'
})

const iconClass = computed(() => {
  return {
    'icon-connected': isConnected.value,
    'icon-connecting': isConnecting.value || isReconnecting.value,
    'icon-disconnected': !isConnected.value && !isConnecting.value && !isReconnecting.value,
    'icon-error': !!error.value
  }
})

const statusText = computed(() => {
  if (isConnecting.value) return '连接中...'
  if (isReconnecting.value) return `重连中... (${reconnectAttempts.value}/${maxReconnectAttempts.value})`
  if (isConnected.value) return '已连接'
  if (error.value) return '连接错误'
  return '未连接'
})

const qualityText = computed(() => {
  switch (connectionQuality.value) {
    case 'good': return '良好'
    case 'poor': return '较差'
    case 'offline': return '离线'
    default: return '未知'
  }
})

// Methods
const handleReconnect = async () => {
  try {
    await connectionStore.reconnect()
  } catch (err) {
    console.error('Manual reconnect failed:', err)
  }
}

const handleDisconnect = async () => {
  try {
    await connectionStore.disconnect()
  } catch (err) {
    console.error('Manual disconnect failed:', err)
  }
}

const handleClearError = () => {
  connectionStore.clearError()
}

const handleSyncOfflineMessages = async () => {
  try {
    await connectionStore.syncOfflineMessages()
  } catch (err) {
    console.error('Sync offline messages failed:', err)
  }
}

const formatTime = (date: Date | null): string => {
  if (!date) return '未知'
  return formatDistanceToNow(date)
}

const toggleDetails = () => {
  showDetails.value = !showDetails.value
}

const startAutoHideTimer = () => {
  if (!props.autoHide) return
  
  clearAutoHideTimer()
  autoHideTimer = setTimeout(() => {
    if (isConnected.value && !showDetails.value) {
      // Auto hide when connected and details not shown
    }
  }, props.autoHideDelay)
}

const clearAutoHideTimer = () => {
  if (autoHideTimer) {
    clearTimeout(autoHideTimer)
    autoHideTimer = null
  }
}

// Lifecycle
onMounted(() => {
  startAutoHideTimer()
})

onUnmounted(() => {
  clearAutoHideTimer()
})

// Expose methods for parent components
defineExpose({
  showDetails: () => { showDetails.value = true },
  hideDetails: () => { showDetails.value = false },
  toggleDetails
})
</script>

<style scoped lang="scss">
.connection-status {
  position: relative;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: rgba(0, 0, 0, 0.05);
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;

  &:hover {
    background: rgba(0, 0, 0, 0.1);
  }
}

.status-icon {
  position: relative;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  transition: all 0.2s ease;

  &.icon-connected {
    background: #52c41a;
  }

  &.icon-connecting {
    background: #1890ff;
  }

  &.icon-disconnected {
    background: #d9d9d9;
  }

  &.icon-error {
    background: #ff4d4f;
  }

  .pulse {
    position: absolute;
    top: -2px;
    left: -2px;
    right: -2px;
    bottom: -2px;
    border-radius: 50%;
    border: 2px solid currentColor;
    animation: pulse 1.5s infinite;
  }
}

.status-text {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.status-panel {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: white;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  min-width: 300px;
  margin-top: 8px;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;

  h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
    color: #333;
  }

  .close-btn {
    background: none;
    border: none;
    font-size: 20px;
    cursor: pointer;
    color: #999;
    padding: 0;
    width: 24px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;

    &:hover {
      color: #333;
    }
  }
}

.panel-content {
  padding: 16px;
}

.status-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;

  &:last-child {
    margin-bottom: 0;
  }

  .label {
    font-size: 14px;
    color: #666;
  }

  .value {
    font-size: 14px;
    font-weight: 500;
    color: #333;

    &.connected {
      color: #52c41a;
    }

    &.connecting, &.reconnecting {
      color: #1890ff;
    }

    &.disconnected {
      color: #999;
    }

    &.error {
      color: #ff4d4f;
    }

    &.quality-good {
      color: #52c41a;
    }

    &.quality-poor {
      color: #faad14;
    }

    &.quality-offline {
      color: #999;
    }
  }
}

.error-message {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  padding: 12px;
  background: #fff2f0;
  border: 1px solid #ffccc7;
  border-radius: 6px;
  margin-top: 12px;

  .error-icon {
    font-size: 16px;
    line-height: 1;
  }

  .error-text {
    font-size: 14px;
    color: #ff4d4f;
    line-height: 1.4;
  }
}

.panel-actions {
  display: flex;
  gap: 8px;
  padding: 16px;
  border-top: 1px solid #f0f0f0;
  flex-wrap: wrap;
}

.action-btn {
  padding: 6px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  background: white;
  color: #333;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s ease;

  &:hover:not(:disabled) {
    border-color: #1890ff;
    color: #1890ff;
  }

  &:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }

  &.retry-btn {
    background: #1890ff;
    color: white;
    border-color: #1890ff;

    &:hover:not(:disabled) {
      background: #40a9ff;
    }
  }

  &.disconnect-btn {
    background: #ff4d4f;
    color: white;
    border-color: #ff4d4f;

    &:hover:not(:disabled) {
      background: #ff7875;
    }
  }

  &.sync-btn {
    background: #52c41a;
    color: white;
    border-color: #52c41a;

    &:hover:not(:disabled) {
      background: #73d13d;
    }
  }
}

.offline-banner {
  position: fixed;
  top: 60px;
  left: 50%;
  transform: translateX(-50%);
  background: #fff7e6;
  border: 1px solid #ffd591;
  border-radius: 6px;
  padding: 12px 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 999;
  max-width: 400px;
}

.banner-content {
  display: flex;
  align-items: center;
  gap: 12px;

  .banner-icon {
    font-size: 16px;
  }

  .banner-text {
    font-size: 14px;
    color: #d46b08;
    flex: 1;
  }

  .banner-action {
    padding: 4px 8px;
    background: #fa8c16;
    color: white;
    border: none;
    border-radius: 4px;
    font-size: 12px;
    cursor: pointer;
    transition: background 0.2s ease;

    &:hover:not(:disabled) {
      background: #d46b08;
    }

    &:disabled {
      opacity: 0.5;
      cursor: not-allowed;
    }
  }
}

.quality-indicator {
  position: absolute;
  top: 50%;
  right: -30px;
  transform: translateY(-50%);
}

.quality-bars {
  display: flex;
  gap: 2px;
  align-items: flex-end;

  .bar {
    width: 3px;
    background: #d9d9d9;
    border-radius: 1px;
    transition: background 0.2s ease;

    &:nth-child(1) { height: 6px; }
    &:nth-child(2) { height: 9px; }
    &:nth-child(3) { height: 12px; }

    &.active {
      background: #52c41a;
    }
  }
}

@keyframes pulse {
  0% {
    opacity: 1;
    transform: scale(1);
  }
  50% {
    opacity: 0.5;
    transform: scale(1.2);
  }
  100% {
    opacity: 1;
    transform: scale(1);
  }
}

// Status-specific styles
.connected {
  .status-text {
    color: #52c41a;
  }
}

.connecting, .reconnecting {
  .status-text {
    color: #1890ff;
  }
}

.disconnected {
  .status-text {
    color: #999;
  }
}

.error {
  .status-text {
    color: #ff4d4f;
  }
}

// Responsive design
@media (max-width: 768px) {
  .status-panel {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 90vw;
    max-width: 400px;
  }

  .panel-actions {
    flex-direction: column;

    .action-btn {
      width: 100%;
    }
  }

  .offline-banner {
    left: 16px;
    right: 16px;
    transform: none;
    max-width: none;
  }
}
</style>